package pizarra.vistas;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * VistaPrincipal.java
 *
 * Created on 18/06/2009, 19:36:50
 */

import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JInternalFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileNameExtensionFilter;

import mobilefeel.AndroidDevice;

import pizarra.Controlador;
/**
 *
 * @author Christian
 */
public class VistaPrincipal extends javax.swing.JFrame {

	private static final long serialVersionUID = 1L;
	private Controlador controlador;
    private List<VistaPizarra> ventanas;
    static final int SEPARACION = 24;
	static int inset = 0;

    /** Creates new form VistaPrincipal */
    public VistaPrincipal(Controlador c) {
        controlador = c;
        try {
        	UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(VistaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(VistaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(VistaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(VistaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        initComponents();

        ventanas = new ArrayList<VistaPizarra>();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {

        desktopPane = new javax.swing.JDesktopPane();
        barraEstadoToolBar = new javax.swing.JToolBar();
        barraEstadoLabel = new javax.swing.JLabel();
        barraEstadoTimer = new javax.swing.Timer(5000, new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
				barraEstadoLabel.setText(" ");
			}
		});
        barraHerramientasToolBar = new javax.swing.JToolBar();
        iniciarButton = new JButton();
        detenerButton = new JButton();
        jSeparator6 = new javax.swing.JToolBar.Separator();
        nuevoButton = new javax.swing.JButton();
        abrirButton = new javax.swing.JButton();
        cerrarButton = new javax.swing.JButton();
        jSeparator8 = new javax.swing.JToolBar.Separator();
        cascadaButton = new javax.swing.JButton();
        mosaicoButton = new javax.swing.JButton();
        jSeparator7 = new javax.swing.JToolBar.Separator();
        contenidoButton = new javax.swing.JButton();
        acercaDeButton = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        archivoMenu = new javax.swing.JMenu();
        iniciarMenuItem = new javax.swing.JMenuItem();
        detenerMenuItem = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        nuevoMenuItem = new javax.swing.JMenuItem();
        abrirMenuItem = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JSeparator();
        cerrarMenuItem = new javax.swing.JMenuItem();
        cerrarTodosMenuItem = new javax.swing.JMenuItem();
        jSeparator5 = new javax.swing.JSeparator();
        salirMenuItem = new javax.swing.JMenuItem();
        verMenu = new javax.swing.JMenu();
        herramientasCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem();
        estadoCheckBoxMenuItem = new javax.swing.JCheckBoxMenuItem();
        ventanaMenu = new javax.swing.JMenu();
        cascadaMenuItem = new javax.swing.JMenuItem();
        mosaicoMenuItem = new javax.swing.JMenuItem();
        organizarMenuItem = new javax.swing.JMenuItem();
        jSeparator3 = new javax.swing.JSeparator();
        ayudaMenu = new javax.swing.JMenu();
        contenidoMenuItem = new javax.swing.JMenuItem();
        jSeparator4 = new javax.swing.JSeparator();
        aboutMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Pizarra Multitouch");
        setMinimumSize(new java.awt.Dimension(800, 600));

        desktopPane.setBackground(getBackground());
        getContentPane().add(desktopPane, java.awt.BorderLayout.CENTER);

        barraEstadoToolBar.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));
        barraEstadoToolBar.setRollover(true);
        barraEstadoTimer.setRepeats(false);
        
        barraEstadoLabel.setText("Pizarra Multitouch");
        barraEstadoToolBar.add(barraEstadoLabel);

        getContentPane().add(barraEstadoToolBar, java.awt.BorderLayout.SOUTH);

        barraHerramientasToolBar.setRollover(true);
        barraHerramientasToolBar.setPreferredSize(new java.awt.Dimension(100, 25));

        iniciarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pizarra/vistas/iconos/31.png"))); // NOI18N
        iniciarButton.setToolTipText("Iniciar Servidor");
        iniciarButton.setFocusable(false);
        iniciarButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        iniciarButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        iniciarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                iniciarButtonActionPerformed(evt);
            }
        });
        barraHerramientasToolBar.add(iniciarButton);
        
        detenerButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pizarra/vistas/iconos/42.png"))); // NOI18N
        detenerButton.setToolTipText("Detener Servidor");
        detenerButton.setFocusable(false);
        detenerButton.setVisible(false);
        detenerButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        detenerButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        detenerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                detenerButtonActionPerformed(evt);
            }
        });
        barraHerramientasToolBar.add(detenerButton);
        
        barraHerramientasToolBar.add(jSeparator6);
        
        nuevoButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pizarra/vistas/iconos/21.png"))); // NOI18N
        nuevoButton.setToolTipText("Nueva Pizarra");
        nuevoButton.setFocusable(false);
        nuevoButton.setEnabled(false);
        nuevoButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        nuevoButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        nuevoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nuevoButtonActionPerformed(evt);
            }
        });
        barraHerramientasToolBar.add(nuevoButton);

        abrirButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pizarra/vistas/iconos/46_1.png"))); // NOI18N
        abrirButton.setToolTipText("Abrir Pizarra...");
        abrirButton.setFocusable(false);
        abrirButton.setEnabled(false);
        abrirButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        abrirButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        abrirButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                abrirButtonActionPerformed(evt);
            }
        });
        barraHerramientasToolBar.add(abrirButton);

        cerrarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pizarra/vistas/iconos/13.png"))); // NOI18N
        cerrarButton.setToolTipText("Cerrar Pizarra Activa");
        cerrarButton.setFocusable(false);
        cerrarButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        cerrarButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        cerrarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cerrarButtonActionPerformed(evt);
            }
        });
        barraHerramientasToolBar.add(cerrarButton);
        barraHerramientasToolBar.add(jSeparator8);

        cascadaButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pizarra/vistas/iconos/18.png"))); // NOI18N
        cascadaButton.setToolTipText("Cascada");
        cascadaButton.setFocusable(false);
        cascadaButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        cascadaButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        cascadaButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cascadaButtonActionPerformed(evt);
            }
        });
        barraHerramientasToolBar.add(cascadaButton);

        mosaicoButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pizarra/vistas/iconos/36.png"))); // NOI18N
        mosaicoButton.setToolTipText("Mosaico");
        mosaicoButton.setFocusable(false);
        mosaicoButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        mosaicoButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        mosaicoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mosaicoButtonActionPerformed(evt);
            }
        });
        barraHerramientasToolBar.add(mosaicoButton);
        barraHerramientasToolBar.add(jSeparator7);

        contenidoButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pizarra/vistas/iconos/15.png"))); // NOI18N
        contenidoButton.setToolTipText("Contenido");
        contenidoButton.setFocusable(false);
        contenidoButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        contenidoButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        contenidoButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				contenidoButtonActionPerformed(e);
			}
		});
        barraHerramientasToolBar.add(contenidoButton);

        acercaDeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pizarra/vistas/iconos/100.png"))); // NOI18N
        acercaDeButton.setToolTipText("Acerca de...");
        acercaDeButton.setFocusable(false);
        acercaDeButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        acercaDeButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        acercaDeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                acercaDeButtonActionPerformed(evt);
            }
        });
        barraHerramientasToolBar.add(acercaDeButton);

        getContentPane().add(barraHerramientasToolBar, java.awt.BorderLayout.NORTH);

        archivoMenu.setText("Archivo");

        iniciarMenuItem.setText("Iniciar Servidor");
        iniciarMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                iniciarMenuItemActionPerformed(evt);
            }
        });
        archivoMenu.add(iniciarMenuItem);

        detenerMenuItem.setText("Detener Servidor");
        detenerMenuItem.setEnabled(false);
        detenerMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                detenerMenuItemActionPerformed(evt);
            }
        });
        archivoMenu.add(detenerMenuItem);
        archivoMenu.add(jSeparator1);

        nuevoMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        nuevoMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pizarra/vistas/iconos/21.png"))); // NOI18N
        nuevoMenuItem.setText("Nueva Pizarra");
        nuevoMenuItem.setEnabled(false);
        nuevoMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nuevoMenuItemActionPerformed(evt);
            }
        });
        archivoMenu.add(nuevoMenuItem);
        
        abrirMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
        abrirMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pizarra/vistas/iconos/46_1.png"))); // NOI18N
        abrirMenuItem.setText("Abrir Pizarra...");
        abrirMenuItem.setEnabled(false);
        abrirMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	abrirMenuItemActionPerformed(evt);
            }
        });
        archivoMenu.add(abrirMenuItem);
        archivoMenu.add(jSeparator2);

        cerrarMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.CTRL_MASK));
        cerrarMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pizarra/vistas/iconos/13.png"))); // NOI18N
        cerrarMenuItem.setText("Cerrar");
        cerrarMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cerrarMenuItemActionPerformed(evt);
            }
        });
        archivoMenu.add(cerrarMenuItem);

        cerrarTodosMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.CTRL_MASK | java.awt.event.InputEvent.SHIFT_MASK));
        cerrarTodosMenuItem.setText("Cerrar Todos");
        cerrarTodosMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cerrarTodosMenuItemActionPerformed(evt);
            }
        });
        archivoMenu.add(cerrarTodosMenuItem);
        archivoMenu.add(jSeparator5);

        salirMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.CTRL_MASK));
        salirMenuItem.setText("Salir");
        salirMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salirMenuItemActionPerformed(evt);
            }
        });
        archivoMenu.add(salirMenuItem);

        menuBar.add(archivoMenu);

        verMenu.setText("Ver");

        herramientasCheckBoxMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_H, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        herramientasCheckBoxMenuItem.setSelected(true);
        herramientasCheckBoxMenuItem.setText("Mostrar Barra Herramientas");
        herramientasCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                herramientasCheckBoxMenuItemActionPerformed(evt);
            }
        });
        verMenu.add(herramientasCheckBoxMenuItem);

        estadoCheckBoxMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        estadoCheckBoxMenuItem.setSelected(true);
        estadoCheckBoxMenuItem.setText("Mostrar Barra Estado");
        estadoCheckBoxMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                estadoCheckBoxMenuItemActionPerformed(evt);
            }
        });
        verMenu.add(estadoCheckBoxMenuItem);

        menuBar.add(verMenu);

        ventanaMenu.setText("Ventana");

        cascadaMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pizarra/vistas/iconos/18.png"))); // NOI18N
        cascadaMenuItem.setText("Cascada");
        cascadaMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cascadaMenuItemActionPerformed(evt);
            }
        });
        ventanaMenu.add(cascadaMenuItem);

        mosaicoMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pizarra/vistas/iconos/36.png"))); // NOI18N
        mosaicoMenuItem.setText("Mosaico");
        mosaicoMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mosaicoMenuItemActionPerformed(evt);
            }
        });
        ventanaMenu.add(mosaicoMenuItem);

        organizarMenuItem.setText("Organizar Íconos");
        organizarMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                organizarMenuItemActionPerformed(evt);
            }
        });
        ventanaMenu.add(organizarMenuItem);
        ventanaMenu.add(jSeparator3);

        menuBar.add(ventanaMenu);

        ayudaMenu.setText("Ayuda");

        contenidoMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
        contenidoMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pizarra/vistas/iconos/15.png"))); // NOI18N
        contenidoMenuItem.setText("Contenido");
        contenidoMenuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				contenidoMenuItemActionPerformed(e);
			}
		});
        ayudaMenu.add(contenidoMenuItem);
        ayudaMenu.add(jSeparator4);

        aboutMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pizarra/vistas/iconos/100.png"))); // NOI18N
        aboutMenuItem.setText("Acerca de...");
        aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aboutMenuItemActionPerformed(evt);
            }
        });
        ayudaMenu.add(aboutMenuItem);

        menuBar.add(ayudaMenu);

        setJMenuBar(menuBar);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public void cerrarFrame(JInternalFrame frame) {
        if (frame != null) {
            for (int i = 0; i < ventanaMenu.getItemCount(); i++) {
                if ((ventanaMenu.getItem(i) != null) && (ventanaMenu.getItem(i).getText().equals(frame.getTitle()))) {
                    ventanaMenu.remove(ventanaMenu.getItem(i));
                            break;
                }
            }
            desktopPane.remove(frame);
        }
        desktopPane.repaint();
    }
    
    public void actualizarFrame(String anterior, String nuevo) {
    	for (int i = 0; i < ventanaMenu.getItemCount(); i++) {
    		if (ventanaMenu.getItem(i) != null && ventanaMenu.getItem(i).getText().equals(anterior)) {
    			ventanaMenu.getItem(i).setText(nuevo);
    			break;
    		}
    	}
    }

    private void herramientasCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_herramientasCheckBoxMenuItemActionPerformed
        barraHerramientasToolBar.setVisible(!barraHerramientasToolBar.isVisible());
    }//GEN-LAST:event_herramientasCheckBoxMenuItemActionPerformed

    private void estadoCheckBoxMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_estadoCheckBoxMenuItemActionPerformed
        barraEstadoToolBar.setVisible(!barraEstadoToolBar.isVisible());
    }//GEN-LAST:event_estadoCheckBoxMenuItemActionPerformed

    private void nuevoMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoMenuItemActionPerformed
        AndroidDevice device = (AndroidDevice) JOptionPane.showInputDialog(this, "Seleccionar dispositivo:", "Nueva Pizarra", JOptionPane.PLAIN_MESSAGE, null, controlador.getDispositivosConectados().toArray(), controlador.getDispositivosConectados().toArray()[0]);
    	if (device != null) {
	        VistaPizarra vp = controlador.doNuevaPizarra(device);
	        ventanas.add(vp);
	        vp.setTitle("Nueva Pizarra " + inset + " - " + device.toString());
	        vp.setVisible(true);
	        desktopPane.add(vp);
	        JMenuItem item = new JMenuItem(vp.getTitle());
	        item.addActionListener(new ActionListener() {
	            public void actionPerformed(ActionEvent e) {
	                JInternalFrame[] frames = desktopPane.getAllFrames();
	                if (frames.length > 0) {
	                    for (int i = 0; i < frames.length; i++) {
	                        if (frames[i].getTitle().equals(((JMenuItem)e.getSource()).getText())) {
	                            try {
	                                frames[i].setSelected(true);
	                            } catch (PropertyVetoException ex) {
	                                Logger.getLogger(VistaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
	                            }
	                            return;
	                        }
	
	                    }
	                }
	            }
	        });
	        ventanaMenu.add(item);
	        try {
	            vp.setSelected(true);
	        } catch (PropertyVetoException ex) {
	            Logger.getLogger(VistaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
	        }
    	}
    }//GEN-LAST:event_nuevoMenuItemActionPerformed

    private void abrirMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoMenuItemActionPerformed
    	JFileChooser fileChooser = new JFileChooser();
		fileChooser.setFileFilter(new FileNameExtensionFilter("Dibujo PMT (*.pmt)", "pmt"));
		fileChooser.setAcceptAllFileFilterUsed(false);
		fileChooser.setDialogTitle("Abrir...");
		if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();
			if (file != null) {
				AndroidDevice device = (AndroidDevice) JOptionPane.showInputDialog(this, "Seleccionar dispositivo:", "Abrir Pizarra", JOptionPane.PLAIN_MESSAGE, null, controlador.getDispositivosConectados().toArray(), controlador.getDispositivosConectados().toArray()[0]);
		    	if (device != null) {
		    		VistaPizarra vp;
					try {
						vp = controlador.doAbrir(device, file);
						ventanas.add(vp);
				        vp.setTitle(file.getName().substring(0, file.getName().indexOf(".")) + " - " + device.toString());
				        vp.setVisible(true);
				        desktopPane.add(vp);
				        JMenuItem item = new JMenuItem(vp.getTitle());
				        item.addActionListener(new ActionListener() {
				            public void actionPerformed(ActionEvent e) {
				                JInternalFrame[] frames = desktopPane.getAllFrames();
				                if (frames.length > 0) {
				                    for (int i = 0; i < frames.length; i++) {
				                        if (frames[i].getTitle().equals(((JMenuItem)e.getSource()).getText())) {
				                            try {
				                                frames[i].setSelected(true);
				                            } catch (PropertyVetoException ex) {
				                                Logger.getLogger(VistaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
				                            }
				                            return;
				                        }
				
				                    }
				                }
				            }
				        });
				        ventanaMenu.add(item);
				        try {
				            vp.setSelected(true);
				        } catch (PropertyVetoException ex) {
				            Logger.getLogger(VistaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
				        }
					} catch (FileNotFoundException e1) {
						JOptionPane.showMessageDialog(this, "Archivo no encontrado.", "Error", JOptionPane.WARNING_MESSAGE);
					} catch (Exception e1) {
						JOptionPane.showMessageDialog(this, "No se pudo abrir el archivo.", "Error", JOptionPane.WARNING_MESSAGE);
					}
		    	}
			}
		}
    }//GEN-LAST:event_nuevoMenuItemActionPerformed

    private void cerrarTodosMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cerrarTodosMenuItemActionPerformed
        desktopPane.removeAll();
        desktopPane.repaint();
        inset = 0;
        if (ventanaMenu.getItemCount() > 4) {
            for (int i = 4; i < ventanaMenu.getItemCount(); i++) {
                ventanaMenu.remove(ventanaMenu.getItem(i));
                i--;
            }
        }
    }//GEN-LAST:event_cerrarTodosMenuItemActionPerformed

    private void cerrarMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cerrarMenuItemActionPerformed
        JInternalFrame sel = desktopPane.getSelectedFrame();
        desktopPane.selectFrame(true);
        cerrarFrame(sel);
    }//GEN-LAST:event_cerrarMenuItemActionPerformed

    private void salirMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salirMenuItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_salirMenuItemActionPerformed

    private void cascadaMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cascadaMenuItemActionPerformed
        int x = 0;
        int y = 0;
        JInternalFrame[] frames = desktopPane.getAllFrames();
        if (frames.length > 0) {
            int alturaFrame = (desktopPane.getBounds().height - 5) - inset * SEPARACION;
            int anchoFrame = (desktopPane.getBounds().width - 5) - inset * SEPARACION;
            for (int i = frames.length - 1; i >= 0; i--) {
                if (!frames[i].isClosed() && frames[i].isIcon()) {
                    try {
                        frames[i].setIcon(false);
                    } catch (PropertyVetoException ignored) {
                    }
                }

                frames[i].setSize(anchoFrame, alturaFrame);
                frames[i].setLocation(x, y);
                x = x + SEPARACION;
                y = y + SEPARACION;
            }
        }
    }//GEN-LAST:event_cascadaMenuItemActionPerformed

    private void mosaicoMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mosaicoMenuItemActionPerformed
        // How many frames do we have?
        JInternalFrame[] frames = desktopPane.getAllFrames();
        if (frames.length > 0) {
            // Determine the necessary grid size
            int sqrt = (int) Math.sqrt(frames.length);
            int rows = sqrt;
            int cols = sqrt;
            if (rows * cols < frames.length) {
              cols++;
              if (rows * cols < frames.length) {
                rows++;
              }
            }

            // Define some initial values for size & location.
            Dimension size = desktopPane.getSize();
            int w = size.width / cols;
            int h = size.height / rows;
            int x = 0;
            int y = 0;

            // Iterate over the frames, deiconifying any iconified frames and then
            // relocating & resizing each.
            for (int i = 0; i < rows; i++) {
              for (int j = 0; j < cols && ((i * cols) + j < frames.length); j++) {
                JInternalFrame f = frames[(i * cols) + j];

                if (!f.isClosed() && f.isIcon()) {
                  try {
                    f.setIcon(false);
                  } catch (PropertyVetoException ignored) {
                  }
                }

                desktopPane.getDesktopManager().resizeFrame(f, x, y, w, h);
                x += w;
              }
              y += h; // start the next row
              x = 0;
            }
        }
    }//GEN-LAST:event_mosaicoMenuItemActionPerformed

    private void organizarMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_organizarMenuItemActionPerformed
        JInternalFrame[] frames = desktopPane.getAllFrames();
        if (frames.length > 0) {
            for (int i = 0; i < frames.length; i++) {
                try {
                    frames[i].setIcon(true);
                } catch (PropertyVetoException ex) {
                    Logger.getLogger(VistaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }//GEN-LAST:event_organizarMenuItemActionPerformed

    private void iniciarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoButtonActionPerformed
        iniciarMenuItem.doClick();
    }//GEN-LAST:event_nuevoButtonActionPerformed
    
    private void detenerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoButtonActionPerformed
        detenerMenuItem.doClick();
    }//GEN-LAST:event_nuevoButtonActionPerformed
    
    private void nuevoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoButtonActionPerformed
        nuevoMenuItem.doClick();
    }//GEN-LAST:event_nuevoButtonActionPerformed

    private void abrirButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoButtonActionPerformed
        abrirMenuItem.doClick();
    }//GEN-LAST:event_nuevoButtonActionPerformed

    private void cerrarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cerrarButtonActionPerformed
        cerrarMenuItem.doClick();
    }//GEN-LAST:event_cerrarButtonActionPerformed

    private void cascadaButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cascadaButtonActionPerformed
        cascadaMenuItem.doClick();
    }//GEN-LAST:event_cascadaButtonActionPerformed

    private void mosaicoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mosaicoButtonActionPerformed
        mosaicoMenuItem.doClick();
    }//GEN-LAST:event_mosaicoButtonActionPerformed

    private void acercaDeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_acercaDeButtonActionPerformed
        aboutMenuItem.doClick();
    }//GEN-LAST:event_acercaDeButtonActionPerformed

    private void contenidoButtonActionPerformed(ActionEvent evt) {
    	contenidoMenuItem.doClick();
    }
    
    private void contenidoMenuItemActionPerformed(ActionEvent evt) {
    	if (Desktop.isDesktopSupported()) {
			try {
				Desktop.getDesktop().open(new File(System.getProperty("user.dir") + "/manual/pizarra.html"));
			} catch (IOException e) {
				JOptionPane.showMessageDialog(this, "Error al abrir Contenido.", "Error", JOptionPane.WARNING_MESSAGE);
			}
    	} else
    		JOptionPane.showMessageDialog(this, "Error al abrir Contenido.", "Error", JOptionPane.WARNING_MESSAGE);
    }
    
    private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutMenuItemActionPerformed
    	JOptionPane.showMessageDialog(this, "Pizarra Multitouch\nMobileFeel SDK for Android\nProyecto Final de Ingeniería UADE\n\n-Gschwind, Nicolás Darío\n-Smirnoff, Christian Alejandro\n\n2011 Todos los derechos reservados", "Acerca de Pizarra Multitouch", JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_aboutMenuItemActionPerformed

    private void iniciarMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_desconectarseMenuItemActionPerformed
    	int puerto = 51460;
    	try {
    		Object puertoStr = JOptionPane.showInputDialog(this, "Ingrese puerto:", "Pizarra Multitouch", JOptionPane.PLAIN_MESSAGE, null, null, "51460");
    		if (puertoStr != null) {
	    		puerto = Integer.parseInt(puertoStr.toString());
	    		controlador.doIniciar(puerto);
	        	servidorIniciado();
    		}
    	} catch (NumberFormatException e) {
    		JOptionPane.showMessageDialog(this, "Puerto no válido.", "Error", JOptionPane.WARNING_MESSAGE);
    	} catch (Exception e) {
			JOptionPane.showMessageDialog(this, "Error al abrir socket.", "Error", JOptionPane.WARNING_MESSAGE);
		}
    }//GEN-LAST:event_desconectarseMenuItemActionPerformed

    private void detenerMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_desconectarseMenuItemActionPerformed
    	try {
	    	controlador.doDetener();
	    	servidorIniciado();
    	} catch (Exception e) {
			JOptionPane.showMessageDialog(this, "Error al cerrar socket.", "Error", JOptionPane.WARNING_MESSAGE);
		}
    }//GEN-LAST:event_desconectarseMenuItemActionPerformed


    public void servidorIniciado() {
        iniciarMenuItem.setEnabled(!iniciarMenuItem.isEnabled());
        detenerMenuItem.setEnabled(!detenerMenuItem.isEnabled());
        iniciarButton.setVisible(!iniciarButton.isVisible());
        detenerButton.setVisible(!detenerButton.isVisible());
    }
    
    public void conexionRecibida() {
        nuevoMenuItem.setEnabled(true);
        abrirMenuItem.setEnabled(true);
        nuevoButton.setEnabled(true);
        abrirButton.setEnabled(true);
    }
    
    public void conexionesCerradas() {
    	nuevoMenuItem.setEnabled(false);
        abrirMenuItem.setEnabled(false);
        nuevoButton.setEnabled(false);
        abrirButton.setEnabled(false);
    }
    
    public void setEstado(String estado) {
        barraEstadoLabel.setText(estado);
        barraEstadoTimer.restart();
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JButton abrirButton;
    private javax.swing.JButton iniciarButton;
    private javax.swing.JButton detenerButton;
    private javax.swing.JMenuItem abrirMenuItem;
    private javax.swing.JButton acercaDeButton;
    private javax.swing.JMenu archivoMenu;
    private javax.swing.JMenu ayudaMenu;
    private javax.swing.JLabel barraEstadoLabel;
    private javax.swing.JToolBar barraEstadoToolBar;
    private javax.swing.Timer barraEstadoTimer;
    private javax.swing.JToolBar barraHerramientasToolBar;
    private javax.swing.JButton cascadaButton;
    private javax.swing.JMenuItem cascadaMenuItem;
    private javax.swing.JButton cerrarButton;
    private javax.swing.JMenuItem cerrarMenuItem;
    private javax.swing.JMenuItem cerrarTodosMenuItem;
    private javax.swing.JMenuItem iniciarMenuItem;
    private javax.swing.JButton contenidoButton;
    private javax.swing.JMenuItem contenidoMenuItem;
    private javax.swing.JMenuItem detenerMenuItem;
    private javax.swing.JDesktopPane desktopPane;
    private javax.swing.JCheckBoxMenuItem estadoCheckBoxMenuItem;
    private javax.swing.JCheckBoxMenuItem herramientasCheckBoxMenuItem;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSeparator jSeparator4;
    private javax.swing.JSeparator jSeparator5;
    private javax.swing.JToolBar.Separator jSeparator6;
    private javax.swing.JToolBar.Separator jSeparator7;
    private javax.swing.JToolBar.Separator jSeparator8;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JButton mosaicoButton;
    private javax.swing.JMenuItem mosaicoMenuItem;
    private javax.swing.JButton nuevoButton;
    private javax.swing.JMenuItem nuevoMenuItem;
    private javax.swing.JMenu verMenu;
    private javax.swing.JMenuItem organizarMenuItem;
    private javax.swing.JMenuItem salirMenuItem;
    private javax.swing.JMenu ventanaMenu;
    // End of variables declaration//GEN-END:variables

}
